<?php
$servername = "localhost";
$username = "talon";
$password = "xhwykzv";
$dbname = "talon";

function getResult($conn, $sql){
    $stmt = $conn->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $result;
}

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // 设置 PDO 错误模式为异常
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    //获取最近6小时数据
    $sql = "SELECT * FROM sensor WHERE time >= DATE_SUB(NOW(), INTERVAL 6 HOUR)"; 
    $result = getResult($conn, $sql);

    //如果获取到的数据少于240条，则获取最近720条数据
    if(empty($result)){
        $sql = "SELECT * FROM (
            SELECT * FROM sensor ORDER BY time DESC LIMIT 720
        ) sub
        ORDER BY time ASC"; 
        $result = getResult($conn, $sql);
    }

    $lastTime = end($result)["time"];

    $time = array();
    $temp = array();
    $humi = array();

    foreach ($result as $row) {
        $time[] = $row["time"];
        $temp[] = $row["temperature"];
        $humi[] = $row["humidity"];
    }
}
catch(PDOException $e) {
    echo "连接失败: " . $e->getMessage();
}

$conn = null;
?>